import type {
  ConfigGetRequest,
  ConfigGetResponse,
  ConfigSetRequest,
  ConfigSetResponse,
} from '@shared/types/ipc'
import { ConfigValidator } from '@shared/types/config'
// 配置管理 IPC 处理器
import { ipcMain } from 'electron'
import { getConfig, resetConfig, updateConfig } from '../config/index'
import { getLogger } from '../logger/index'
import { getConfigService } from '../services/config-service'

export function setupConfigHandlers(): void {
  const logger = getLogger()

  // 配置：获取
  ipcMain.handle('config:get', async (event, request: ConfigGetRequest): Promise<ConfigGetResponse> => {
    try {
      void event
      const config = getConfig()

      if (request.keys && request.keys.length > 0) {
        // 获取指定键的配置
        const result: Record<string, any> = {}
        for (const key of request.keys) {
          const value = getNestedValue(config, key)
          if (value !== undefined) {
            result[key] = value
          }
        }
        return { success: true, config: result }
      }
      else {
        // 获取所有配置
        return { success: true, config }
      }
    }
    catch (error: any) {
      logger.error('获取配置失败:', error)
      return {
        success: false,
        config: {},
        error: error.message,
      }
    }
  })

  // 配置：设置
  ipcMain.handle('config:set', async (event, request: ConfigSetRequest): Promise<ConfigSetResponse> => {
    try {
      void event
      const currentConfig = getConfig()

      // 合并配置
      const newConfig = mergeConfig(currentConfig, request.config)

      // 验证配置
      if (request.validate !== false) {
        const errors = ConfigValidator.validateConfig(newConfig)
        if (errors.length > 0) {
          return {
            success: false,
            message: '配置验证失败',
            validation_errors: errors,
          }
        }
      }

      // 更新配置
      await updateConfig(request.config)

      logger.info('✅ 配置已更新', { keys: Object.keys(request.config) })

      return {
        success: true,
        message: '配置已更新',
      }
    }
    catch (error: any) {
      logger.error('设置配置失败:', error)
      return {
        success: false,
        message: '设置配置失败',
        error: error.message,
      }
    }
  })

  // 配置：重置为默认值
  ipcMain.handle('config:reset', async () => {
    try {
      // 使用新的重置函数
      await resetConfig()

      logger.info('🔄 配置已重置为默认值')

      return {
        success: true,
        message: '配置已重置为默认值',
      }
    }
    catch (error: any) {
      logger.error('重置配置失败:', error)
      return {
        success: false,
        message: '重置配置失败',
        error: error.message,
      }
    }
  })

  // 配置：验证
  ipcMain.handle('config:validate', async (event, config: any) => {
    try {
      void event
      const errors = ConfigValidator.validateConfig(config)

      return {
        success: errors.length === 0,
        valid: errors.length === 0,
        errors,
      }
    }
    catch (error: any) {
      logger.error('验证配置失败:', error)
      return {
        success: false,
        valid: false,
        errors: [error.message],
      }
    }
  })

  // 配置项：获取所有
  ipcMain.handle('config:list', async (event, options: any = {}) => {
    try {
      void event
      const configService = getConfigService()
      const configs = await configService.getAllConfigs(options)

      return {
        success: true,
        configs,
      }
    }
    catch (error: any) {
      logger.error('获取配置列表失败:', error)
      return {
        success: false,
        configs: [],
        error: error.message,
      }
    }
  })

  // 配置项：创建
  ipcMain.handle('config:create', async (event, request: any) => {
    try {
      void event
      const configService = getConfigService()
      const config = await configService.createConfig(request)

      return {
        success: true,
        config,
        message: '配置项创建成功',
      }
    }
    catch (error: any) {
      logger.error('创建配置项失败:', error)
      return {
        success: false,
        error: error.message,
      }
    }
  })

  // 配置项：更新
  ipcMain.handle('config:update', async (event, { config_key, ...updates }: any) => {
    try {
      void event
      const configService = getConfigService()
      const config = await configService.updateConfig(config_key, updates)

      return {
        success: true,
        config,
        message: '配置项更新成功',
      }
    }
    catch (error: any) {
      logger.error('更新配置项失败:', error)
      return {
        success: false,
        error: error.message,
      }
    }
  })

  // 配置项：删除
  ipcMain.handle('config:delete', async (event, { config_key }: any) => {
    try {
      void event
      const configService = getConfigService()
      await configService.deleteConfig(config_key)

      return {
        success: true,
        message: '配置项删除成功',
      }
    }
    catch (error: any) {
      logger.error('删除配置项失败:', error)
      return {
        success: false,
        error: error.message,
      }
    }
  })
}

// 获取嵌套对象的值
function getNestedValue(obj: any, path: string): any {
  return path.split('.').reduce((current, key) => {
    return current && current[key] !== undefined ? current[key] : undefined
  }, obj)
}

// 设置嵌套对象的值
// removed unused _setNestedValue

// 深度合并配置对象
function mergeConfig(target: any, source: any): any {
  const result = { ...target }

  for (const key in source) {
    if (source[key] !== null && typeof source[key] === 'object' && !Array.isArray(source[key])) {
      result[key] = mergeConfig(target[key] || {}, source[key])
    }
    else {
      result[key] = source[key]
    }
  }

  return result
}
